package com.ncmmall.api.apis.mall;

import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.security.Securitys;
import com.feijin.commons.lang.Dates;
import com.ncmmall.domain.business.message.Message;
import com.ncmmall.domain.business.message.QMessage;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息通知api
 *
 * @author likaikai
 * @date 2019-07-14 18:10
 */
@RestController
@RequestMapping("/message")
public class MessageApi {

    @Autowired
    private QueryChannelService queryChannelService;

    private Logger logger = LoggerFactory.getLogger(MessageApi.class);

    /**
     * 消息列表
     *
     * @return
     */
    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") int type, HttpServletRequest request, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "20") int pageSize) {

        Result result = new Result();

        try {
            WebUser member = Securitys.user(request);
            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);

            Map<String, Object> map = new HashMap<>();
            map.put("type", type);

            String sql = "";
            if (type == 1) {
                sql = "select * from mall_message where platformType = 1 and type = :type order by createTime desc ";
            } else {
                sql = buildSql("select * from mall_message where platformType = 1 and type = :type ", type, member, map);
            }

            QueryPage<Message> page = queryChannelService.queryPageEntity(sql, pageRequest.setParams(map), Message.class);
            for (Message message : page.getResult()) {
                message.setContent(null);
            }

            return result.ok().inject(page);

        } catch (Exception e) {
            logger.error("[获取消息列表异常]", e);
            return result.fail().setMsg("网络请求异常");
        }

    }

    /**
     * 条件查询
     *
     * @param sql
     * @param type
     * @param member
     * @param map
     * @return
     */
    private String buildSql(String sql, int type, WebUser member, Map<String, Object> map) {
        sql += " and member_id = :mid";
        map.put("mid", member.getId());
        sql += " order by createTime desc";

        return sql;
    }


    /**
     * 消息详情
     *
     * @return
     */
    @GetMapping("/detail")
    public Result detail(long id) {

        Result result = new Result();
        try {
            Message message = queryChannelService.findOne(QMessage.message.id.eq(id), Message.class);
            return result.ok().inject(message);

        } catch (Exception e) {
            logger.error("[获取消息详情异常]", e);
            return result.fail().setMsg("网络请求异常");
        }

    }


    /**
     * 最新消息列表
     *
     * @return
     */
    @GetMapping("/last")
    public Result last(HttpServletRequest request) {
        Result result = new Result();

        try {
            WebUser member = Securitys.user(request);

            Map<String, Object> data = new HashMap<>();

            //系统消息
            Message systemMessage;

            //普通会员
            systemMessage = queryChannelService.queryOneEntity("select * from mall_message where platformType = 1 and type = 1 order by createTime desc limit 1", Collections.emptyMap(), Message.class);

            if (systemMessage != null) {
                data.put("systemMessage", ImmutableMap.of("title", systemMessage.getTitle(), "createTime", Dates.transDateToStrTime(systemMessage.getCreateTime())));
            } else {
                data.put("systemMessage", null);
            }


            //订单消息
            Message orderMessage = queryChannelService.queryOneEntity("select * from mall_message where platformType = 1 and type = 2 and member_id = :mid order by createTime desc limit 1", ImmutableMap.of("mid", member.getId()), Message.class);
            if (orderMessage != null) {
                data.put("orderMessage", ImmutableMap.of("title", orderMessage.getTitle(), "createTime", Dates.transDateToStrTime(orderMessage.getCreateTime())));
            } else {
                data.put("orderMessage", null);
            }

            return result.ok().inject(data);

        } catch (Exception e) {
            logger.error("[获取最新消息异常]", e);
            return result.fail().setMsg("网络请求异常");
        }

    }


}
